from PySide6.QtWidgets import *
from PySide6.QtCore import *
from .TypeSelect import TypeSelect
from .layout.VBoxLayout import VBoxLayout
from enums.WidgetType import WidgetType


class ScriptContent(QWidget):
    def __init__(self, data=None, initType=None):
        self.mainLayout = QVBoxLayout()
        super().__init__()

        self.initType = initType
        self.mainLayout.setAlignment(Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignLeft)

        self.scriptLayout = VBoxLayout()
        self.mainLayout.addLayout(self.scriptLayout)

        self.addLayout = QVBoxLayout()
        self.btnAdd = QPushButton('+')
        self.btnAdd.setFixedSize(40, 40)
        self.btnAdd.clicked.connect(self.add)
        self.addLayout.addWidget(self.btnAdd)
        self.mainLayout.addLayout(self.addLayout)

        self.setLayout(self.mainLayout)

        if data is not None:
            for datum in data:
                self.addOperate(datum['type'], datum)

    @property
    def widgets(self):
        return self.scriptLayout.children()

    def add(self):
        typeSelect = TypeSelect(self.addOperate)
        typeSelect.exec()

    def insert(self, widget):
        self.tempWidget = widget
        typeSelect = TypeSelect(self.insertWidget)
        typeSelect.exec()

    def insertWidget(self, addType, data=None):
        from .scriptWidgets.Factory import Factory as ScriptWidgetFactory
        widget = ScriptWidgetFactory.getByType(addType, self.initType)
        widget.setOnDelete(self.deleteWidget)
        widget.setOnInsert(self.insert)
        self.scriptLayout.insertAfterWidget(self.tempWidget, widget)

    def addOperate(self, addType, data=None):
        from .scriptWidgets.Factory import Factory as ScriptWidgetFactory
        widget = ScriptWidgetFactory.getByType(addType, self.initType)
        if data is not None:
            widget.data = data

        widget.setOnDelete(self.deleteWidget)
        widget.setOnInsert(self.insert)
        self.scriptLayout.addWidget(widget)
        if data is None and addType not in [
            WidgetType.WAIT.value, WidgetType.WAIT_TEXT.value,
            WidgetType.WAIT_PIC.value
        ]:
            self.addOperate(WidgetType.WAIT.value)

    def deleteWidget(self, widget):
        self.scriptLayout.removeWidget(widget)
